import React, {
    useState,
    useEffect
} from "react";
import {getQueryVariable,removeToken,removeIdentity} from "../../util/public";
import BtnAlert from "../component/btnAlert";
import fetch from "../../util/fetch";
import $ from "jquery";
import md5 from "md5";
import "./index.scss";
import logoUrl from '../images/top_logo.png'
import IdentityIcon from '../../identityIcon/index'
import {
    lgAlert, LgSplitLine, LgDropdown, LgTopBarContainer, BackToOfficialBlock,
    IdentityBlock,
    LogoutBlock,
    MessageBlock,
    UserBlock, SystemInfo, createClassName, SystemInfoProps
  } from "lancoo-web-ui";
  import { requireSystemTheme, setSystemTheme } from 'lancoo-web-ui';
const {classNames} = createClassName("lg-top-bar")
const {classNames: pageClassNames} = createClassName("lg-top-bar-example")

function Header(props){
    const workInfo = JSON.parse(sessionStorage.getItem("workInfo"))
    
    const [userInfo, setUserInfo] = useState({});
    const [identityInfo, setIdentityInfo] = useState({});
    const [alertInfo, setAlertInfo] = useState({});
    
    //获取工作平台以及消息中心信息
    const getWorkInfo = () => {
        let baseUrl = sessionStorage.getItem('baseUrl')
        let token = sessionStorage.getItem('token') || getQueryVariable('lg_tk')
        let mdToken210 = md5('210').split('').reverse().join('')
        fetch.get({
        url: baseUrl + '/BaseApi/Global/GetSubSystemsMainServerBySubjectID',
            params: {
                appid: 210,
                access_token: mdToken210,
                sysIDs: '210'
            }
        }).then(result => result.json()).then(res => {
            if (res.StatusCode == 200 && res.Data) {
                let data = {
                    webSvrAddr: res.Data[0].WebSvrAddr,
                    wsSvrAddr: res.Data[0].WsSvrAddr
                }
                sessionStorage.setItem('messageInfo', JSON.stringify(data))
                sessionStorage.setItem('PsnMgrToken', token);//用户Token
                sessionStorage.setItem('PsnMgrMainServerAddr', baseUrl); //基础平台IP地址和端口号 形如：http://192.168.129.1:30103/
                sessionStorage.setItem('PsnMgrLgAssistantAddr', res.Data[0].WebSvrAddr); //个人信息管理系统Web站点IP地址和端口号 形如：http://192.168.129.1:10103/
                let messageUrl = data.webSvrAddr
                let arr = [messageUrl + '/PsnMgr/LgAssistant/js/jquery-1.7.2.min.js',
                messageUrl + "/PsnMgr/LgAssistant/assets/jquery.pagination.js",
                messageUrl + "/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js",
                messageUrl + "/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css"
                ].reverse()
                loadScriptOrCss(arr);
            }
        })
    }
    const loadScriptOrCss = (urlArr, num) => {//同步引入动态js和css函数
        if (!num) {
            num = urlArr.length;
        }
        //正则判断是否是css;
        var reg = RegExp(/.css/);
        var scriptOrCss

        if (reg.test(urlArr[num - 1])) {
            // 动态生成css
            scriptOrCss = document.createElement('link');
            scriptOrCss.type = 'text/css';
            scriptOrCss.async = 'async';
            scriptOrCss.href = urlArr[num - 1];
            scriptOrCss.rel = "stylesheet";
            document.getElementsByTagName("head")[0].appendChild(scriptOrCss);

        } else {
            // 动态生成js
            scriptOrCss = document.createElement('script');
            scriptOrCss.type = 'text/javascript';
            scriptOrCss.async = 'async';
            scriptOrCss.src = urlArr[num - 1];
            document.body.appendChild(scriptOrCss);
        }
        if (scriptOrCss.readyState) {
            //IE下
            scriptOrCss.onreadystatechange = function () {
                if (scriptOrCss.readyState == 'complete' || scriptOrCss.readyState == 'loaded') {
                    scriptOrCss.onreadystatechange = null;
                    num--;
                    if (num == 0) {
                    } else {
                        loadScriptOrCss(urlArr, num);
                    }
                }
            }
        } else {
            //其他浏览器
            scriptOrCss.onload = function () {
                num--;
                if (num == 0) {

                } else {
                    loadScriptOrCss(urlArr, num);
                }
            }
        }
    }
    const toPerson = () => {
        let baseUrl = sessionStorage.getItem('baseUrl')
        // window.open(baseUrl + '/UserMgr/PersonalMgr/Default.aspx?lg_tk=' + token, '_blank');

        let token = sessionStorage.getItem('token')
        let pathName = "html/personalMgr"
        window.open(baseUrl + `${pathName}?lg_tk=${token}`, '_blank');

    }
    const showMessage = () => {
        $("#Assistant_infoCenter").click();
    }
    const toHelp = () => {
        let token = sessionStorage.getItem('token')
        // window.open(window.BasicProxy + '/dutyWeekHelp/index.html?lg_tk=' + token, '_blank');
        window.open(`${sessionStorage.getItem('baseUrl')}help/static/article-detail/48/?lg_tk=${token}`, '_blank')
    }
    const quitMethod = () => {
        console.log(userInfo)
        setAlertInfo({
            visible: true,
            title: "是否退出登录？",
            onCancel: function(){
                setAlertInfo({});
            },
            onOk: function(){
                let token = sessionStorage.getItem('token');
                fetch
                .get({
                  url: window.BasicProxy + "api/common/user/logout", 
                  params: { token, userId:  userInfo.userId}
                })
                .then((res)=>res.json())
                .then((res)=>{
                    let str = removeToken(window.location.href);
                    // str = removeIdentity(str);
                    sessionStorage.removeItem("token");
                    window.location.href = sessionStorage.getItem('baseUrl') + '/login.html?lg_sysid=E47&lg_preurl=' + encodeURIComponent(str);
                    
                })
            }
        })
    }
    const toPlatFrom = () => {
        console.log(JSON.parse(sessionStorage.getItem('sysInfo')))
        let token = sessionStorage.getItem('token')
        let baseUrl = JSON.parse(sessionStorage.getItem('sysInfo')).itemUrl
        window.open(baseUrl + 'html/index/?lg_tk=' + token, '_blank');
    }
    useEffect(()=>{
        //引入消息中心
        if(sessionStorage.getItem("userInfo")){
            let info = JSON.parse(sessionStorage.getItem("userInfo"));
            setUserInfo(info);
            if(sessionStorage.getItem("identityInfo")){
                setIdentityInfo(JSON.parse(sessionStorage.getItem("identityInfo")));
                console.log("identityInfo", JSON.parse(sessionStorage.getItem("identityInfo")));
            }
        }
        getWorkInfo();

        // if(!["IC0001", "IC0002"].includes(sessionStorage.getItem("identityCode"))){
          document.title = getQueryVariable('isManage') == 1 ? "值周管理": "值周"
        // }
    }, []);

    useEffect(() => {
        let basicPlatformAddress = sessionStorage.getItem("baseUrl"); //基础平台地址
        let appId = '252'; //子系统ID
        let token = sessionStorage.getItem("token"); //用户令牌
        /**
        * @description  : 此处用于非代理下的子系统，如另外需要部署的子系统调用；可以参考一卡通
        * @waring  : 注：此方法有请求，会导致部分系统产生跨域无法正常调用的情况，请子系统对接基础平台后参考调用形式四
        * @waring  : 注：如果控制台打印 “[web-ui] 缓存未获取到用户主题,请自行调用设置主题色工具,如已添加请忽略此打印” 请用此方法；
        */
        window?._defaultThemeColor?.error(() => requireSystemTheme(basicPlatformAddress, appId, token))
    }, [])

    const [systemHeaderInfo, setSystemHeaderInfo] = useState({
        type: 'A',
        logoUrl: logoUrl,
        systemName: getQueryVariable('isManage') == 1 ? "值周管理": "值周",
        // version: "安防版",
        // role: "管理端",
        // children:(<LgDropdown
        //     className={classNames('system-select')}
        //     value={this.state.currentTerm}
        //     datalist={this.state.term}
        //     SelectOption={this.handSelectOption}
        // />)
    })
    return (
        
        <div className="app_header" id="test">
            {/* <div className="header_container">
                <div className="app_left">
                  <div className="app_logo"></div>
                  <div className="app_name">{["IC0001", "IC0002"].includes(sessionStorage.getItem("identityCode"))? "值周管理": "值周"}</div>
                </div>
                <div className="header_btn">
                    <span className="btn_work" onClick={toPlatFrom}>返回办公平台</span>
                    <span className="slice_line"></span>
                    <span className="btn_message">
                        <i id="Assistant_infoCenter"></i>
                        <span onClick={showMessage}>消息</span>
                    </span>
                    <span className="btn_help" onClick={toHelp}>帮助</span>
                    <span className="slice_line"></span>
                    <div className="user_info" onClick={toPerson}>
                        <i className="user_avatar" style={{
                            backgroundImage: `url('${decodeURIComponent(userInfo.photoPath)}')`
                        }}></i>
                        <span className="user_name">{decodeURIComponent(userInfo.userName)}</span>
                        {
                            identityInfo.isPreset?
                            <img className="user_image" src={identityInfo.identityImg} alt="身份"/>:
                            <span className="user_identity" style={{
                                backgroundImage: `url('${identityInfo.identityImg}')`
                            }} title={identityInfo.identityName}>{identityInfo.identityName}</span>
                        }
                    </div>
                    <i className="quitlogo" onClick={quitMethod}></i>
                </div>
            </div> */}
            <LgTopBarContainer type="C">
            <SystemInfo {...systemHeaderInfo}>
        </SystemInfo>
            {/* <div className="header_container">
                <div className="app_left">
                  <div className="app_logo"></div>
                  <div className="app_name">{["IC0001", "IC0002"].includes(sessionStorage.getItem("identityCode"))? "值周管理": "值周"}</div>
                </div>
    
            </div> */}
        <div className={(classNames("right"))}>
          <BackToOfficialBlock handClick={toPlatFrom}/>
          <LgSplitLine />
            <span className="top-btn">
              <i id="Assistant_infoCenter"></i>
                <span onClick={showMessage}>消息</span>
            </span>
            <span className="btn_help" onClick={toHelp}>帮助</span>
          <LgSplitLine margin={'0 10px'}/>
          <div className="user-container" onClick={toPerson}>
            <UserBlock userImageUrl={userInfo.photoPath} userName={userInfo.userName} />
          </div>
          {/* {
              identityInfo.isPreset?
              <IdentityBlock identityImgUrl={identityInfo.identityImg}>
              </IdentityBlock>:
              <IdentityBlock identityImgUrl={identityInfo.identityImg}>
                  <span className={(classNames("define-identity"))}>{identityInfo.identityName}</span>
              </IdentityBlock>
          } */}
          <IdentityIcon userType={userInfo.userType}></IdentityIcon>
          <LogoutBlock handClick={quitMethod}/>
        </div>
      </LgTopBarContainer>

            <BtnAlert 
            visible={alertInfo.visible} 
            title={alertInfo.title} 
            smallTitle={alertInfo.smallTitle}
            onOk={alertInfo.onOk}
            onCancel={alertInfo.onCancel} />
        </div>
        
    )
}

export default Header;